package com.example.jinmingwu.a180524_intentbroacast;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;



public class MainActivity extends AppCompatActivity {

    private Button myButton=null;
    //Intent动作字符串唯一标识要广播的事件（该字符串必须独一无二）
    private final String nobody="Who.care.the.name";

    private Button bindingButton=null;
    private Button unbindingButton=null;
    private SMSReceiverActivity smsReceiver=null;

    private static final String SMS_ACTION="android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //broacast in xml
        myButton=(Button)findViewById(R.id.button);
        myButton.setOnClickListener(new MyButtonListener());

        //broacast in java
        bindingButton=(Button)findViewById(R.id.bindingButton);
        bindingButton.setOnClickListener(new bindReceiverListener());
        unbindingButton=(Button)findViewById(R.id.unbindingButton);
        unbindingButton.setOnClickListener(new unbindReceiverListener());
    }


    class bindReceiverListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            //生成一个BroiadcastReceiver对象
            smsReceiver=new SMSReceiverActivity();
            //生成一个IntentFilter对象
            IntentFilter filter=new IntentFilter();
            //生成一个InterFilter对象
            filter.addAction(SMS_ACTION);
            //将BroadcastReceiver对象注册到系统当中
            MainActivity.this.registerReceiver(smsReceiver,filter);
        }
    }

    class unbindReceiverListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            //解除BroadcastReceiver对象的注册
            MainActivity.this.unregisterReceiver(smsReceiver);
        }
    }


    class MyButtonListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            //生成一个Intent对象
            Intent i=new Intent(nobody);
            //在Intent对象当中添加一个键值对（额外增添的本地类型值）
            i.putExtra("testIntent","11111111111");
            sendBroadcast(i);
        }
    }
}
